<?php

class RegistrationController extends dmq\Controller
{
	protected $useDb = true;

	public function doControll()
	{
		$this->title( 'Registration' );


		if( $this->view->triedToRegister() )
		{
			require_once 'lib/Validation.php';
			$validate = new Validation();

			try
			{
				if ( !$validate->username( $this->view->getUsername() ) )
				{
					throw new Exception( 'Invalid username! Valid length: 4-20, Valid characters: A-z 0-0 _' );
				}

				if ( !$validate->password( $this->view->getPassword() ) )
				{
					throw new Exception( 'Invalid password! Valid length: 6-20, Do not use spaces!' );
				}

				if ( $this->view->getPassword() !== $this->view->getPasswordRepeat() )
				{
					throw new Exception( 'Password and it\'s repeat do not match!' );
				}

				if ( !$validate->email( $this->view->getEmail() ) )
				{
					throw new Exception( 'Invalid e-mail address!' );
				}

				$this->model->register( $this->view->getUsername(), $this->view->getPassword(), $this->view->getEmail() );
				$this->view->Message( 'You are now registered! Feel free to <a href="index.php?c=login">Login</a>.' );
			}
			catch ( Exception $e )
			{
				$this->view->error( $e->getMessage() );
			}
		}

		
		$this->view->buildRegistrationForm();
		
		$this->view->printErrors( '<p class="error"><span>Error :(</span> _ERROR_</p>' . "\r\n" );
		$this->view->printMessages( '<p class="message"><span>Success \o/</span> _MESSAGE_</p>' . "\r\n" );
	}
}
